<template>
  <view>
    <view v-if="!isTimeout" class="flex flex-column justify-between pt-10" id="container" :style="{minHeight:`calc(100vh - ${top}px - 88rpx)`}">
      <u-collapse :accordion="false" :head-style="{marginBottom: 30+'rpx'}" ref="refCollapse">
        <u-collapse-item v-for="(item, index) in equipmentWithHidden" :key="index" :ref="'collapse' + index" v-show="!item.hidden" open>
          <template slot="title">
            <view class="text-center bg-19BE6B br-32 p-lr-22 p-tb-17 color-fff font-bold ml-20">
              <text class="max-w-460 text-ellipsis-2">{{item.deviceName}}</text>
            </view>
          </template>
          <check-item
            v-for="(standardListItem,standardListIndex) in item.projectList"
            :key="standardListIndex"
            :standardListItem="standardListItem"
            :hospitalId="hospitalId"
            :workOrderId="workOrderId"
            :deviceName="item.deviceName"
            :workOrderName="item.workOrderName"
            :isUseCache="isUseCache"
            :hidden="item.hidden"
            ref="checkItem"
            @formData="formData"
            @uploadCachePicFail="uploadCachePicFail"
            @uploadStatusChange="uploadStatusChange"
          >
          </check-item>
        </u-collapse-item>
<!--        <collapse-item @collapseDone="collapseDone(index)" v-for="(item, index) in equipmentWithHidden" :key="index" :ref="'collapse' + index" open>
          <template slot="title">
            <view class="text-center bg-19BE6B br-32 p-lr-22 p-tb-17 color-fff font-bold ml-20">
              <text class="max-w-460 text-ellipsis-2">{{item.deviceName}}</text>
            </view>
          </template>

          <check-item
            v-for="(standardListItem,standardListIndex) in item.projectList"
            :key="standardListIndex"
            :standardListItem="standardListItem"
            :hospitalId="hospitalId"
            :workOrderId="workOrderId"
            :deviceName="item.deviceName"
            :workOrderName="item.workOrderName"
            :isUseCache="isUseCache"
            @calcHeight="calcHeight('collapse' + index)"
            ref="checkItem"
            @formData="formData"
            @uploadCachePicFail="uploadCachePicFail"
          >
          </check-item>


        </collapse-item>-->
      </u-collapse>
      <view>
        <view class="w-full flex justify-center mb-30">
          <view class="w-200 h-80 br-10 bg-2DB7F5 color-fff fz-30 text-center lh-80 mr-50"
                v-if="currentPage !== 1"
                @tap.stop="handlePre">上一页</view>
          <view class="w-200 h-80 br-10 bg-2DB7F5 color-fff fz-30 text-center lh-80"
                v-if="currentPage * paginationPageSize < equipmentList.length"
                @tap.stop="handleNext">下一页</view>
        </view>
        <view class="flex justify-center sticky bottom-0 bg-fff z-99 h-190 pt-30">
          <view class="w-250 h-80 br-10 bg-19BE6B color-fff fz-30 text-center lh-80" @tap="confirm">
            <text>提交</text>
          </view>
        </view>
      </view>
    </view>
    <!--空照片模态框 -->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="isEmptyPhoto">
      <view class="h-150 flex align-center justify-center font-bold">
        <image class="mr-20 w-38 h-38" src="@/static/images/mine/error.png"></image>
        <text>请上传照片！</text>
      </view>
    </u-modal>


    <!--是否保存缓存弹窗-->
    <u-modal v-model="isCustomBackModalShow" :show-confirm-button="false" :show-title="false" border-radius="20"
             mask-close-able>
      <view class="w-full flex flex-column align-center p-lr-50">
        <view class="lh-center color-333 fz-30 fw-700 p-tb-42 w-full">修改未提交，是否继续退出该页面？</view>
        <view class="w-full">
          <u-checkbox-group>
            <u-checkbox
                v-model="item.checked"
                v-for="(item, index) in isCache"
                :key="index"
                :name="item.name"
            >{{item.name}}</u-checkbox>
          </u-checkbox-group>
        </view>
        <view class="flex align-center justify-center m-tb-50">
          <view class="border-2D8CF0 w-120 h-60 border-box color-fff bg-2D8CF0 fz-28 text-center lh-60 br-5 mr-50"
                @tap="navigateBack">
            <text>确定</text>
          </view>
          <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5"
                @tap="isCustomBackModalShow = false">
            <text>取消</text>
          </view>
        </view>
      </view>
    </u-modal>

    <!--是否使用本地缓存弹窗-->
    <u-modal v-model="isUseCacheModal" :show-confirm-button="false" :show-title="false" border-radius="20"
             mask-close-able>
      <view class="w-full flex flex-column align-center p-lr-50">
        <view class="lh-center color-333 fz-30 fw-700 p-tb-42 border-bottom-CCCCCC w-full">本地有缓存，是否使用？</view>
        <view class="flex align-center justify-center m-tb-50">
          <view class="border-2D8CF0 w-120 h-60 border-box color-fff bg-2D8CF0 fz-28 text-center lh-60 br-5 mr-50"
                @tap="useCache(true)">
            <text>确定</text>
          </view>
          <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5"
                @tap="useCache(false)">
            <text>取消</text>
          </view>
        </view>
      </view>
    </u-modal>

    <!--异常提示模态框-->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="isModalShow">
      <view class="flex align-center justify-center fz-30 font-bold color-333333 p-12 min-h-100">
        <image class="mr-20 min-w-38 max-w-38 h-38 ml-20" src="@/static/images/mine/error.png"></image>
        <text class="break-all lh-30">{{modalContent}}</text>
      </view>
    </u-modal>


    <u-mask :show="isShowMask" :mask-click-able="false">
      <view class="flex justify-center align-center h-full color-fff fz-32 font-bold">
        <text>{{maskContent}}</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-mask>

    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="isOneClickModalShow">
      <view class="h-150 flex align-center justify-center fz-30 font-bold color-333333">
        <image class="mr-20 w-38 h-38" src="@/static/images/mine/success.png"></image>
        <text>已全选正常，请继续填写数值与拍照</text>
      </view>
    </u-modal>

    <!--图片上传中模态框-->
    <!-- #ifndef MP-WEIXIN -->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" v-model="isUploading">
      <view class="h-200 flex flex-column align-center justify-center font-bold color-888888 lh-33 bg-fff">
        <text class="mb-10">图片上传中</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-modal>
    <!-- #endif -->

    <!--微信小程序使用cover-view解决textarea层级过高问题-->

    <!-- #ifdef MP-WEIXIN -->
    <cover-view class="fixed top0 w-full min-100vh bg-00000060 flex align-center justify-center z-999" v-show="isUploading" @touchmove.stop.prevent="">
      <cover-view class="h-200 w-600 br-20 text-center lh-200 font-bold color-888888 lh-33 bg-fff">
        图片上传中
      </cover-view>
    </cover-view>
    <!-- #endif -->

    <empty-icon v-if="isTimeout"  content="网络错误"></empty-icon>
  </view>
</template>

<script>
import CheckItem from "./components/CheckItem.vue";
import CollapseItem from "./components/CollapseItem.vue";
import getNavBarHeight from "@/mixins/getNavBarHeight";
import {listWorkOrderDevice} from "@/api/maintenance/workOrderDevice";
import {submit} from "@/api/maintenance/task";
import {mapGetters} from 'vuex'
import EmptyIcon from "../../components/EmptyIcon/EmptyIcon";
export default {
  name: "roomCheck",
  components: {EmptyIcon, CollapseItem, CheckItem},
  mixins:[getNavBarHeight],
  onLoad(options){
    this.maskContent = ''
    this.workOrderId = options.workOrderId
    this.hospitalId = options.hospitalId
    listWorkOrderDevice({roomId:options.roomId, workOrderId:options.workOrderId}).then(res => {
      this.equipmentList = res.data
      this.$nextTick(() => {
        this.$refs.refCollapse.init()
        this.isShowMask = false
      })
    }).catch(err => {
      this.isShowMask = false
      this.isTimeout = true
    })
    this.isUseCacheModal = !!this.maintenanceCache[this.workOrderId]
  },
  onBackPress(e){
    if(this.allowBack) return false
    //页面是否被修改
    let isChanged = false
    this.$refs.checkItem.forEach(item => {
      isChanged = item.isChange() || isChanged
    })
    if(isChanged){
      this.isCustomBackModalShow = true
    }else{
      return false
    }
    return true
  },
  data(){
    return {
      isUploading:false,
      equipmentList: [],
      standardResult:[],
      workOrderId:'',
      hospitalId: null,
      isEmptyPhoto:false,//必须上传照片的标准没有上传照片提示
      isCustomBackModalShow: false,//返回按钮确认模态框,
      isShowMask: true,
      maskContent: '',
      allowBack: false,
      isUseCache: undefined, //是否使用缓存
      isUseCacheModal: false, //是否使用缓存弹窗
      isCache: [{
        name: '暂存该页面信息',
        checked: true
      }],
      timer: '',
      isModalShow: false,
      modalContent: '',
      isTimeout: false,
      isOneClickModalShow: false,
      isUploadCachePicSuccess: false,
      currentPage: 1,
    }
  },
  computed: {
    ...mapGetters(['maintenanceCache', 'paginationUseful', 'paginationPageSize']),
    equipmentWithHidden() {
      return this.equipmentList.map((item, idx) => ({
        ...item,
        hidden: this.paginationUseful && (idx < (this.currentPage - 1) * this.paginationPageSize || idx >= this.currentPage * this.paginationPageSize)
      }))
    }
  },
  methods:{
    uploadStatusChange(bool){
      this.isUploading = bool
    },
    uploadCachePicFail(){
      this.isShowMask = false
      this.isUploadCachePicSuccess = false
    },
    useCache(value){
      this.isUseCache = value
      this.isUseCacheModal = false
    },
    //等待所有折叠项展开后隐藏mask
    collapseDone(index){
      if(index + 1 === this.equipmentList.length){
        this.isShowMask = false
      }
    },
    navigateBack(){
      this.allowBack = true
      //缓存数据
      if(this.isCache[0].checked){
        this.$refs.checkItem.forEach(item => {
          item.setStorage()
        })
      }
      //清空缓存数据
      else{
        this.removeMaintenanceCache()
      }
      this.$tab.navigateBack()
    },
    removeMaintenanceCache(){
      let maintenanceCache = this.maintenanceCache
      if(maintenanceCache[this.workOrderId]){
        delete maintenanceCache[this.workOrderId]
      }
      this.$store.commit('SET_MAINTENANCECACHE', maintenanceCache)
    },
    // calcHeight(id){
    //   this.$nextTick(() => {
    //     this.$refs[id][0].calcHeight()
    //   })
    // },
    async handlePre() {
      this.maskContent = ''
      this.isShowMask = true
      await new Promise((resolve) => {
        this.$nextTick(() => {setTimeout(() => {resolve()}, 20)})
      })
      this.currentPage--
      await new Promise((resolve) => {
        this.$nextTick(() => {setTimeout(() => {resolve()}, 20)})
      })
      this.isShowMask = false
    },
    async handleNext() {
      this.maskContent = ''
      this.isShowMask = true
      await new Promise((resolve) => {
        this.$nextTick(() => {setTimeout(() => {resolve()}, 20)})
      })
      this.currentPage++
      await new Promise((resolve) => {
        this.$nextTick(() => {setTimeout(() => {resolve()}, 20)})
      })
      this.isShowMask = false
    },
    async confirm(){
      this.isUploadCachePicSuccess = true
      this.maskContent = '提交中...'
      this.isShowMask = true
      await new Promise((resolve, reject) => {
        this.$refs.checkItem.forEach(item => item.emitData())
        this.timer = setInterval(() => {
          if(this.standardResult.length === this.$refs.checkItem.length ) {
            resolve()
            clearInterval(this.timer)	// 上传操作完成，消除阻塞
          }
        },1)
      })
      //未上传图片
      if(this.standardResult.some(item => {
        return (item.isTakePhoto && !item.ossIdList.length && item.result)
      })){
        this.isEmptyPhoto = true
        this.isShowMask = false
        this.standardResult = []
      }
      //有必填项未填
      else if(this.standardResult.some(item => {
        return (item.result.indexOf('已清洗') > -1 && !item.washValue && item.washValue !==0) || (item.result.indexOf('已更换') > -1 && !item.replaceValue)
      })){
        this.isShowMask = false
        this.isModalShow = true
        this.modalContent = '有必填项未填！'
        this.standardResult = []
      }
      else if(this.standardResult.some(item => {
        if (item.result.indexOf('已更换') === -1) {return false}
        const device = this.equipmentList.find(({workOrderDeviceId}) => workOrderDeviceId === item.workOrderDeviceId)
        const project = device.projectList.find(({workOrderDeviceProjectId}) => workOrderDeviceProjectId === item.workOrderDeviceProjectId)
        return `${item.replaceValue}`.indexOf('.') !== -1 || item.replaceValue > project.projectReplaceValue || item.replaceValue < 1
      })) {
        this.standardResult.forEach(item => {
          if (item.result.indexOf('已更换') === -1) {return}
          const device = this.equipmentList.find(({workOrderDeviceId}) => workOrderDeviceId === item.workOrderDeviceId)
          const project = device.projectList.find(({workOrderDeviceProjectId}) => workOrderDeviceProjectId === item.workOrderDeviceProjectId)
          if (`${item.replaceValue}`.indexOf('.') !== -1 || item.replaceValue > project.projectReplaceValue || item.replaceValue < 1) {
            this.isShowMask = false
            this.isModalShow = true
            this.modalContent = `${device.deviceName} 的 ${project.partName} 替换数量应填入 1-${project.projectReplaceValue} 的整数`
            this.standardResult = []
            throw '打断forEach'
          }
        })
      }
      else{
        if(!this.isUploadCachePicSuccess) {
          this.isShowMask = false
          this.isModalShow = true
          this.modalContent = '提交失败，请重试'
          this.standardResult = []
          return
        }
        submit(this.standardResult).then(res => {
          this.isShowMask = false
          if(res.code === 200){
            this.allowBack = true
            this.removeMaintenanceCache()
            this.$tab.navigateBack()
          }else{
            this.modalContent = '提交失败，'+(res.msg || '请重试')
            this.isModalShow = true
          }
        }).catch((err) => {
          this.isShowMask = false
          this.isModalShow = true
          this.modalContent = '提交失败，请重试'
        }).finally(()=>{
          this.standardResult = []
        })
      }
    },
    formData(data){
      this.standardResult.push({...data,workOrderId:this.workOrderId})
    }
  },
  beforeDestroy(){
    clearInterval(this.timer)
  }
}
</script>

<style lang="scss">
page{
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
/deep/ .u-collapse-head {
  background-color: #fff;
  padding:30rpx 0;
  border-bottom:2rpx solid #ccc
}
/deep/ .u-size-medium{
  background-color: #2D8CF0 !important;
  color: #ffffff !important;
  border-color: #2D8CF0 !important;
  border: 0 !important;
  padding: 0 !important;
  height: 60rpx !important;
  width: 120rpx !important;
}
</style>
